package cn.lanqiao.springbootproject.config;

import cn.lanqiao.springbootproject.mapper.ArticleMapper;
import cn.lanqiao.springbootproject.mapper.UserArticleMapper;
import cn.lanqiao.springbootproject.vo.ArticleVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;

@Slf4j
@Component
public class RedisInitPreLoad implements ApplicationRunner {

    @Autowired
    ArticleMapper articleMapper;

    @Autowired
    UserArticleMapper userArticleMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Value("${article.like.key}")
    String ARTICLE_LIKE_COUNT_KEY;

    @Value("${article.like.id}")
    String ARTICLE_LIKE_ID;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("开始缓存预热...");
        log.info("从MySQL中读取文章列表");
        List<ArticleVO> articleVOList = articleMapper.queryByPage();
        log.info("删除Redis原有的数据");
        redisTemplate.delete(ARTICLE_LIKE_COUNT_KEY);
        log.info("将文章列表写入到Redis");
        for (ArticleVO articleVO : articleVOList) {
            redisTemplate.opsForHash().put(ARTICLE_LIKE_COUNT_KEY, ARTICLE_LIKE_ID + ":" + articleVO.getArticleId(), articleVO.getTotalLikeCount());
            HashSet set = userArticleMapper.queryByArticleId(articleVO.getArticleId());
            if(set == null) set = new HashSet();
            redisTemplate.opsForValue().set(ARTICLE_LIKE_ID + ":" + articleVO.getArticleId(),set);
        }
        log.debug("缓存预热完成!");
    }
}
